import Foundation

class TraceStorage {
    private let fileManager = FileManager.default
    private let queue = DispatchQueue(label: "com.vichat.trace.storage", qos: .background)
    
    private var cachePath: String {
        let paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
        let cachesDirectory = paths[0]
        return (cachesDirectory as NSString).appendingPathComponent("com.vichat.trace")
    }
    
    private var eventsFilePath: String {
        return (cachePath as NSString).appendingPathComponent("events.json")
    }
    
    init() {
        createDirectoryIfNeeded()
    }
    
    private func createDirectoryIfNeeded() {
        if !fileManager.fileExists(atPath: cachePath) {
            do {
                try fileManager.createDirectory(atPath: cachePath, withIntermediateDirectories: true, attributes: nil)
            } catch {
                print("Failed to create trace cache directory: \(error)")
            }
        }
    }
    
    func saveEvent(_ event: TraceEvent) {
        queue.async { [weak self] in
            guard let self = self else { return }
            
            var events = self.loadEvents()
            events.append(event)
            
            // 检查是否超过最大缓存事件数
            let maxEvents = TraceManager.shared.config.cacheStrategy.maxEvents
            if events.count > maxEvents {
                events = Array(events.suffix(maxEvents))
            }
            
            self.saveEvents(events)
        }
    }
    
    func loadEvents() -> [TraceEvent] {
        if !fileManager.fileExists(atPath: eventsFilePath) {
            return []
        }
        
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: eventsFilePath))
            let events = try JSONDecoder().decode([TraceEvent].self, from: data)
            
            // 过滤掉超过最大缓存天数的事件
            let maxDays = TraceManager.shared.config.cacheStrategy.maxDays
            let cutoffDate = Date().timeIntervalSince1970 - TimeInterval(maxDays * 24 * 60 * 60)
            return events.filter { $0.timestamp >= cutoffDate }
        } catch {
            print("Failed to load trace events: \(error)")
            return []
        }
    }
    
    func saveEvents(_ events: [TraceEvent]) {
        do {
            let data = try JSONEncoder().encode(events)
            try data.write(to: URL(fileURLWithPath: eventsFilePath))
        } catch {
            print("Failed to save trace events: \(error)")
        }
    }
    
    func clearEvents() {
        queue.async { [weak self] in
            guard let self = self else { return }
            self.saveEvents([])
        }
    }
    
    func removeEvents(_ events: [TraceEvent]) {
        queue.async { [weak self] in
            guard let self = self else { return }
            
            let currentEvents = self.loadEvents()
            let eventIds = Set(events.map { $0.eventId })
            let remainingEvents = currentEvents.filter { !eventIds.contains($0.eventId) }
            
            self.saveEvents(remainingEvents)
        }
    }
}